import numpy as np
import matplotlib.pyplot as plt
from dezero import Variable,models,optimizers
import dezero.functions as F
import dezero.layers as L

#创建数据
np.random.seed(0)
x = np.random.rand(100,1)
y = np.random.rand(100,1) + np.sin(2 * np.pi * x)

#超参调整
lr = 0.2
epoch = 10000
hidden_size = 10

#运用多层感知器创建
model = models.MLP((hidden_size,1))
#设置优化器为SGD随机梯度下降法
optimizer = optimizers.SGD(lr)
optimizer.setup(model)

#开始训练
for i in range(epoch):
    y_pred = model(x)
    loss = F.mean_squared_error(y,y_pred)

    model.cleargrads()
    loss.backward()
    #使用优化器进行自动更新
    optimizer.update()

#plot
plt.scatter(x,y)
plt.xlabel('x')
plt.ylabel('y')

t = np.arange(0, 1, 0.01)
tt = np.expand_dims(t,1)
y_pred = model(tt)
plt.plot(t,y_pred.data,color='black')

plt.show()